package com.yinhai.activity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.cmcc.groupcontacts.MainApp;
import com.littlec.sdk.entity.CMGroup;
import com.littlec.sdk.entity.CMMember;
import com.littlec.sdk.listener.CMGroupListener;
import com.littlec.sdk.manager.CMIMHelper;
import com.lz.util.Utils;
import com.yinhai.asynctask.BaseTask;
import com.yinhai.constant.UrlConstant;
import com.yinhai.model.ContactsUser;
import com.yinhai.service.ContactUserServiceImpl;
import com.yinhai.util.NullUtils;
import com.yinhai.util.Util;
import com.yinhai.view.CustomGridView;

/**
 * 添加群组
 * 
 * @author lixh
 *
 */
public class ChatAddGroupActivity extends Activity {
    private CustomGridView gridView;
    
    private List<Map<String, Object>> datas = new ArrayList<Map<String, Object>>();
    
    private SimpleAdapter adapter;
    
    private boolean itemDeleteFlag = false;
    
    private List<String> phoneList = new ArrayList<String>();
    
    private List<String> delPhoneList = new ArrayList<String>();
    
    private String groupID;
    
    private List<CMMember> cmMembers;
    
    private EditText editText;
    
    private TextView tvtest;
    
    private Context context;
    
    private ContactUserServiceImpl contactUserService;
    
    private ContactsUser contactuser;
    
    private AQuery aq;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_group);
        Intent intent = this.getIntent();
        contactUserService = new ContactUserServiceImpl(this);
        contactuser = contactUserService.findOnlineContactsUserByIMUserName(Util.getUserInfo(this).getIm_user_name());
        aq = new AQuery(this);
        groupID = intent.getStringExtra("groupID");
        
        gridView = (CustomGridView)findViewById(R.id.gridview);
        editText = (EditText)findViewById(R.id.group_name);
        tvtest = (TextView)findViewById(R.id.tvtest);
        context = ChatAddGroupActivity.this;
        initData();
        adapter =
            new SimpleAdapter(this, datas, R.layout.gridview_group_item, new String[] {"name"}, new int[] {R.id.title}) {
                public View getView(int position, View convertView, ViewGroup parent) {
                    View view = super.getView(position, convertView, parent);
                    Map<String, Object> map = datas.get(position);
                    if (Boolean.valueOf(datas.get(position).get("deleteFlag").toString())) {
                        view.findViewById(R.id.btn_delete).setVisibility(View.VISIBLE);
                    } else {
                        view.findViewById(R.id.btn_delete).setVisibility(View.GONE);
                    }
                    if (map.get("userPhone") != null && !map.get("userPhone").equals("")) {
                        aq.id(view.findViewById(R.id.img)).image(UrlConstant.LOCAL_URI + "getPhoto?phone="
                            + map.get("userPhone"),
                            Utils.getImageOptions(ChatAddGroupActivity.this, R.drawable.tel_photo, Utils.IsImgSize));
                    } else {
                        aq.id(view.findViewById(R.id.img)).image(UrlConstant.LOCAL_URI + "getPhoto?phone="
                            + map.get("id"),
                            Utils.getImageOptions(ChatAddGroupActivity.this, R.drawable.tel_photo, Utils.IsImgSize));
                    }
                    
                    return view;
                }
            };
        
        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int posion, long arg3) {
                if (Boolean.valueOf(datas.get(posion).get("deleteFlag").toString())) {
                    String userPhone =
                        datas.get(posion).get("userPhone") == null ? "" : datas.get(posion).get("userPhone").toString();
                    if (NullUtils.isNotEmpty(userPhone)) {
                        if (delPhoneList.size() > 0) {
                            if (!delPhoneList.contains(datas.get(posion).get("userPhone").toString())) {
                                delPhoneList.add(datas.get(posion).get("userPhone").toString());
                            }
                        } else {
                            delPhoneList.add(datas.get(posion).get("userPhone").toString());
                        }
                    }
                    datas.remove(posion);
                    phoneList.remove(posion);
                    itemDeleteFlag = false;
                    for (Map<String, Object> map : datas) {
                        map.put("deleteFlag", itemDeleteFlag);
                    }
                    adapter.notifyDataSetChanged();
                } else {
                    String userPhone =
                        datas.get(posion).get("userPhone") == null ? "" : datas.get(posion).get("userPhone").toString();
                    if (NullUtils.isNotEmpty(userPhone)) {
                        Intent it = new Intent(context, OnlineContactDetailActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("userId", userPhone);
                        it.putExtras(bundle);
                        context.startActivity(it);
                    }
                    
                }
                
            }
        });
        gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            
            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                itemDeleteFlag = true;
                for (Map<String, Object> map : datas) {
                    map.put("deleteFlag", itemDeleteFlag);
                }
                adapter.notifyDataSetChanged();
                return true;
            }
        });
        gridView.setOnTouchBlankPositionListener(new CustomGridView.OnTouchBlankPositionListener() {
            
            @Override
            public void onTouchBlank(MotionEvent event) {
                itemDeleteFlag = false;
                for (Map<String, Object> map : datas) {
                    map.put("deleteFlag", itemDeleteFlag);
                }
                adapter.notifyDataSetChanged();
            }
        });
    }
    
    public void initData() {
        if (NullUtils.isEmpty(groupID)) {
            tvtest.setText("新建群组");
            return;
        }
        editText.setText(CMIMHelper.getCmGroupManager().getGroupNamefromServer(groupID));
        
        tvtest.setText("修改群组");
        cmMembers = CMIMHelper.getCmGroupManager().getGroupMembersfromServer(groupID);
        
        for (CMMember member : cmMembers) {
            ContactsUser contactsUser = contactUserService.findOnlineContactsUserByIMUserName(member.getMemberId());
            Map<String, Object> map1 = new HashMap<String, Object>();
            map1.put("id", member.getMemberId());
            map1.put("name", member.getMemberNick());
            map1.put("userPhone", contactsUser != null ? contactsUser.getImUserName() : "");
            map1.put("deleteFlag", false);
            datas.add(map1);
        }
        
    }
    
    // 返回
    public void doBack(View view) {
        onBackPressed();
    }
    
    // 添加人员
    public void doAdd(View view) {
        itemDeleteFlag = false;
        for (Map<String, Object> map : datas) {
            map.put("deleteFlag", itemDeleteFlag);
        }
        adapter.notifyDataSetChanged();
        Intent intent = new Intent(this, ContactActivity.class);
        intent.putExtra("userType", 2);
        intent.putExtra("isMutiCheck", true);
        intent.putExtra("userSize", 99);
        startActivityForResult(intent, 123456);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 123456 && resultCode == RESULT_OK) {
            for (ContactsUser user : (List<ContactsUser>)data.getSerializableExtra("data")) {
                if (phoneList.contains(user.getTelPhone())) {
                    continue;
                }
                
                phoneList.add(user.getTelPhone());
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("id", user.getImUserName());
                map.put("name", user.getName());
                map.put("userPhone", user.getTelPhone());
                map.put("deleteFlag", false);
                datas.add(map);
            }
            adapter.notifyDataSetChanged();
        }
    }
    
    public void doSubmit(View view) {
        if (!Util.isConnect(this)) {
            Util.showMsg(this, "请检查网络设置");
            return;
        }
        if (MainApp.isIMConnecteStatus != 2) {
            Util.showMsg(this, "请重新登录即时通讯");
            return;
        }
        if ("".equals(editText.getText().toString().trim()) || editText.getText().toString().trim().length() > 50) {
            Toast.makeText(this, "群名称为1到50个字符", Toast.LENGTH_SHORT).show();
            return;
        }
        if (datas.size() < 2 || datas.size() > 100) {
            Toast.makeText(this, "群成员数量2到100人之间", Toast.LENGTH_SHORT).show();
            return;
        }
        new BaseTask<String, String, Boolean>(this, NullUtils.isEmpty(groupID) ? "群组新建中，请稍等...." : "群组信息更新中，请稍等.....") {
            @Override
            protected void onSuccess(Boolean result) {
                if (result) {
                   
                }
            }
            @Override
            protected Boolean doInBack(String... params)
                throws Exception {
                
                // 新增
                if (NullUtils.isEmpty(groupID)) {
                    try {
                        // 调用创建群接口
                        HashMap<String, String> membersMap = new HashMap<String, String>();
                        for (Map<String, Object> map : datas) {
                            membersMap.put(map.get("id").toString(), map.get("name").toString());
                        }
                        
                        CMGroup cmGroup =
                            CMIMHelper.getCmGroupManager().createGroup(editText.getText().toString().trim(),
                                editText.getText().toString().trim(),
                                contactuser.getName(),
                                membersMap,new CMGroupListener.OnAddGroupListener(){

									@Override
									public void onSuccess(
											List<CMMember> members,
											String groupId) {
											Util.showMsg(ChatAddGroupActivity.this, "操作成功");
						                    Intent intent = new Intent();
						                    intent.putExtra("groupName", editText.getText().toString().trim());
						                    setResult(RESULT_OK, intent);
						                    finish();
									}

									@Override
									public void onFailed(String groupId) {
										  Util.showMsg(ChatAddGroupActivity.this, "群组创建失败");
									}
                            	
                            });
                        return true;
                    } catch (Exception e) {
                        Util.showMsg(ChatAddGroupActivity.this, "群组创建失败");
                        return false;
                    }
                } else {
//                    if (!CMIMHelper.getCmGroupManager()
//                        .getGroupNamefromServer(groupID)
//                        .equals(editText.getText().toString().trim())) {
//                        try {
//                            CMIMHelper.getCmGroupManager().changeGroupName(groupID,
//                                editText.getText().toString().trim());
//                        } catch (Exception e) {
//                            Util.showMsg(ChatAddGroupActivity.this, "群组名称修改失败");
//                            return false;
//                        }
//                    }
                	  HashMap<String, String> membersMap = new HashMap<String, String>();
                      for (Map<String, Object> map : datas) {
                          membersMap.put(map.get("id").toString(), map.get("name").toString());
                      }
                    CMIMHelper.getCmGroupManager().modifyGroup(groupID,editText.getText().toString().trim(),membersMap,new CMGroupListener.OnAddGroupListener(){

						@Override
						public void onSuccess(
								List<CMMember> members,
								String groupId) {
								Util.showMsg(ChatAddGroupActivity.this, "操作成功");
			                    Intent intent = new Intent();
			                    intent.putExtra("groupName", editText.getText().toString().trim());
			                    setResult(RESULT_OK, intent);
			                    finish();
						}

						@Override
						public void onFailed(String groupId) {
							  Util.showMsg(ChatAddGroupActivity.this, "群组修改失败");
						}
                	
                });
//                    
//                    List<String> preMembers = new ArrayList<String>();
//                    List<String> newMembers = new ArrayList<String>();
//                    List<Map<String, Object>> addMembers = new ArrayList<Map<String, Object>>();// 添加成员
//                    List<CMMember> removeMembers = new ArrayList<CMMember>();// 删除成员
//                    if (NullUtils.isEmpty(cmMembers)) {
//                        cmMembers = new ArrayList<CMMember>();
//                    }
//                    for (CMMember member : cmMembers) {
//                        preMembers.add(member.getMemberId());
//                    }
//                    for (Map<String, Object> map : datas) {
//                        newMembers.add(map.get("id").toString());
//                        if (!preMembers.contains(map.get("id").toString())) {
//                            addMembers.add(map);
//                        }
//                    }
//                    for (CMMember member : cmMembers) {
//                        if (!newMembers.contains(member.getMemberId())) {
//                            removeMembers.add(member);
//                        }
//                    }
//                    // 处理新增
//                    if (NullUtils.isNotEmpty(addMembers)) {
//                        HashMap<String, String> membersMap = new HashMap<String, String>();
//                        for (Map<String, Object> map : addMembers) {
//                            membersMap.put(map.get("id").toString(), map.get("name").toString());
//                        }
//                        try {
//                            CMIMHelper.getCmGroupManager().inviteMembersToGroup(groupID, membersMap);
//                        } catch (Exception e) {
//                            Util.showMsg(ChatAddGroupActivity.this, "添加群成员失败");
//                            return false;
//                        }
//                    }
//                    // 处理删除
//                    if (NullUtils.isNotEmpty(removeMembers)) {
//                        // TODO 删除未实现
//                        // CMIMHelper.getCmGroupManager().inviteMembersToGroup(groupId, memberNickMap)
//                    }
                    return true;
                }
            }
        }.execute();
        
    }
}
